package com.travel.travel_springboot_web.controller;

import com.travel.travel_springboot_web.entity.User;
import com.travel.travel_springboot_web.service.UserService;
import com.travel.travel_springboot_web.utils.JwtUtil;
import com.travel.travel_springboot_web.utils.TokenUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/user")
@CrossOrigin(
    originPatterns = {"http://localhost:*", "http://127.0.0.1:*"},
    methods = {RequestMethod.GET, RequestMethod.POST, RequestMethod.OPTIONS},
    allowCredentials = "true"
)
public class UserController {
    
    private static final Logger logger = LoggerFactory.getLogger(UserController.class);
    
    @Autowired
    private UserService userService;
    
    @Autowired
    private TokenUtil tokenUtil;
    
    @Autowired
    private JwtUtil jwtUtil;
    
    @PostMapping("/login")
    public Map<String, Object> login(@RequestBody User user) {
        Map<String, Object> result = new HashMap<>();
        try {
            User loginUser = userService.login(user.getCode());
            result.put("code", 200);
            result.put("message", "success");
            result.put("data", loginUser);
        } catch (Exception e) {
            logger.error("Login failed: ", e);
            result.put("code", 500);
            result.put("message", e.getMessage());
        }
        return result;
    }
    
    @PutMapping("/profile")
    public Map<String, Object> updateProfile(@RequestBody User user) {
        Map<String, Object> result = new HashMap<>();
        try {
            User updatedUser = userService.updateProfile(user);
            result.put("code", 200);
            result.put("message", "success");
            result.put("data", updatedUser);
        } catch (Exception e) {
            logger.error("Update profile failed: ", e);
            result.put("code", 500);
            result.put("message", e.getMessage());
        }
        return result;
    }
    
    @PostMapping("/logout")
    public Map<String, Object> logout(@RequestHeader(value = "Authorization", required = false) String authHeader) {
        Map<String, Object> result = new HashMap<>();
        try {
            // 提取并验证token
            String token = tokenUtil.extractToken(authHeader);
            
            // 从token中获取用户ID
            Long userId = jwtUtil.getUserIdFromToken(token);
            
            // 执行退出操作
            userService.logout(token, userId);
            
            result.put("code", 200);
            result.put("message", "success");
        } catch (Exception e) {
            logger.error("Logout failed: ", e);
            result.put("code", 401);
            result.put("message", e.getMessage());
        }
        return result;
    }
    
    @GetMapping("/info")
    public Map<String, Object> getUserInfo(
            @RequestHeader(value = "Authorization", required = false) String authHeader) {
        Map<String, Object> result = new HashMap<>();
        try {
            // 提取并验证token
            String token = tokenUtil.extractToken(authHeader);
            
            // 从token中获取用户ID
            Long userId = jwtUtil.getUserIdFromToken(token);
            logger.info("Getting user info for user: {}", userId);
            
            if (userId == null) {
                throw new RuntimeException("请先登录");
            }
            
            // 获取用户信息
            User user = userService.getUserInfo(userId);
            if (user == null) {
                throw new RuntimeException("用户不存在");
            }
            
            // 构建返回数据 - 返回所有非敏感信息
            Map<String, Object> data = new HashMap<>();
            data.put("id", user.getId());
            data.put("username", user.getUsername());
            data.put("nickname", user.getNickname());
            data.put("avatar", user.getAvatar());
            data.put("role", user.getRole());
            data.put("status", user.getStatus());
            data.put("name", user.getName());     // 添加姓名
            data.put("phone", user.getPhone());   // 添加电话
            data.put("createdAt", user.getCreatedAt());
            data.put("updatedAt", user.getUpdatedAt());
            
            result.put("code", 200);
            result.put("message", "success");
            result.put("data", data);
        } catch (Exception e) {
            logger.error("Failed to get user info: ", e);
            result.put("code", e.getMessage().contains("请先登录") ? 401 : 500);
            result.put("message", e.getMessage());
        }
        return result;
    }
    
    @PutMapping("/info")
    public Map<String, Object> updateUserInfo(
            @RequestBody Map<String, String> params,
            @RequestHeader(value = "Authorization", required = false) String authHeader) {
        Map<String, Object> result = new HashMap<>();
        try {
            // 提取并验证token
            String token = tokenUtil.extractToken(authHeader);
            
            // 从token中获取用户ID
            Long userId = jwtUtil.getUserIdFromToken(token);
            logger.info("Updating user info for user: {}", userId);
            
            if (userId == null) {
                throw new RuntimeException("请先登录");
            }
            
            // 获取请求参数
            String name = params.get("name");
            String phone = params.get("phone");
            
            // 验证参数
            if (name == null || name.trim().isEmpty()) {
                throw new RuntimeException("姓名不能为空");
            }
            if (phone == null || phone.trim().isEmpty()) {
                throw new RuntimeException("电话号码不能为空");
            }
            
            // 更新用户信息
            User updatedUser = userService.updateUserInfo(userId, name, phone);
            
            result.put("code", 200);
            result.put("message", "success");
            result.put("data", updatedUser);
        } catch (Exception e) {
            logger.error("Failed to update user info: ", e);
            result.put("code", e.getMessage().contains("请先登录") ? 401 : 500);
            result.put("message", e.getMessage());
        }
        return result;
    }
} 